package com.ruoyi.lottery.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.lottery.domain.LotActivity;
import com.ruoyi.lottery.service.ILotActivityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Component
public class LotActivityTask {

    @Autowired
    private ILotActivityService lotActivityService;

    private static final Logger log = LoggerFactory.getLogger(LotActivityTask.class);

    @Scheduled(cron = "0 0 0 * * ?")
    public void execute() {
        log.info("[活动业务]: -----------------开始修改过期活动的状态-----------------");

        // 0: 得到当前时间的时间戳
        long currentGetTime = new Date().getTime();

        // 1: 先查询没有过期的活期
        LambdaQueryWrapper<LotActivity> wrapper = Wrappers.lambdaQuery(LotActivity.class).eq(LotActivity::getStatus, LotActivity.ACTIVITY_STATUS_NORMAL);
        List<LotActivity> list = lotActivityService.list(wrapper);

        // 遍历集合
        Iterator<LotActivity> iterator = list.iterator();
        while (iterator.hasNext()) {
            LotActivity activity = iterator.next();

            // 2: 判断 当前时间的时间戳 是否小于 活动结束的时间戳; 小于: 活动没有过期
            if (currentGetTime < activity.getEndTime().getTime()) {
                // 没有过期的活动从集合中删除
                iterator.remove();
            } else {
                // 过期的活动修改状态为过去
                activity.setStatus(LotActivity.ACTIVITY_STATUS_EXPIRE);
            }
        }

        lotActivityService.updateBatchById(list);

        log.error("[活动业务]: -----------------过期活动状态修改完成-----------------");
    }
}
